package com.dctp.common.disruptor;

import com.dctp.common.vo.FundFlowVo;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FundFlowDisruptor {

    private static final Logger logger = LoggerFactory.getLogger(FundFlowDisruptor.class);

    private static Disruptor<FundFlowEvent> disruptor;
    private static RingBuffer<FundFlowEvent> ringBuffer;

    public static void start() {

        logger.info("FundFlowDisruptor start...");
        int bufferSize = 1024 * 8; // RingBuffer 大小（必须是 2 的幂）
        ExecutorService executor = Executors.newSingleThreadExecutor();
        disruptor = new Disruptor<>(
                new FundFlowEventFactory(),
                bufferSize,
                executor,
                ProducerType.MULTI, // 多生产者（多接口线程写入）
                new BlockingWaitStrategy()
        );

        disruptor.handleEventsWith(new FundFlowEventHandler());
        disruptor.start();
        ringBuffer = disruptor.getRingBuffer();
    }

    /** ✅ 下单接口调用这里发布订单事件 */
    public static void publish(FundFlowVo fundFlowVo) {
        long seq = ringBuffer.next();
        try {
            FundFlowEvent event = ringBuffer.get(seq);
            event.setOrder(fundFlowVo);
        } finally {
            ringBuffer.publish(seq);
        }
    }

    public static void stop() {
        disruptor.shutdown();
    }
}
